/**
 * @filename:BoxingController Jan 9, 2024
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2020 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.controller;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.domain.SysFile;
import com.wonder.admin.service.SysAdminService;
import com.wonder.admin.service.SysFileService;
import com.wonder.app.domain.Boxing;
import com.wonder.app.mapper.BoxingDao;
import com.wonder.app.service.BoxingService;
import com.wonder.app.request.BoxingRequest;

import com.wonder.common.utils.file.FileUtils;
import com.wonder.config.MqttProviderConfig;
import com.wonder.config.MqttReceiveConfig;
import com.wonder.framework.authorization.CheckAdminToken;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <p>说明： 波形程序管理API接口层</P>
 * @version: 1.1.0
 * @author: Wonder
 * @time    Jan 9, 2024
 *
 */
@Api(tags = "波形程序管理")
@RestController
@RequestMapping("/app/Boxing")
public class BoxingController {

	@Autowired
	private BoxingService boxingService;

	@Autowired
	private MqttReceiveConfig mqttReceiveConfig;

	@Autowired
	private BoxingDao boxingDao;
	@Autowired
	private CheckAdminToken checkAdminToken;
	@Autowired
	private SysAdminService adminService;

	@Autowired
	private MqttProviderConfig providerConfig;

	@Autowired
	private SysFileService sysFileService;



	@ApiOperation(value = "波形程序管理列表")
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public Map<String,Object> index(@RequestBody BoxingRequest boxingRequest) {
		Page<Boxing> page = new Page<Boxing>(boxingRequest.getPage(), boxingRequest.getLimit());
		IPage<Boxing> list = boxingService.selectList(boxingRequest, page);
		
		Map<String,Object> retMap=new HashMap<>();
		retMap.put("data",CommonPage.restPage(list));
		
  
		return AjaxMap.success(retMap);
	}
	
	/**
	 * @explain 修改排序开关
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/updateExt")
	@ApiOperation(value = "修改排序开关", notes = "作者：Wonder")
	public AjaxResult<Boxing> updateExt(@RequestBody Boxing entity){
		if (null!=entity) {
			boolean rsg = boxingService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 添加
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/add")
	@ApiOperation(value = "添加", notes = "作者：Wonder")
	public AjaxResult<Boxing> add(HttpServletRequest request , @RequestBody Boxing entity)  throws Exception
	{

		if (null!=entity)
		{
			//拼接附件名称
			String FileNames = "";
			if(entity.getBxprocedure()!=null)
				entity.setBxprocedure_table(JSON.toJSON(entity.getBxprocedure()).toString());
			int Filesl = entity.getBxprocedure().size();
			//拼接波形名称
			for( int i = 0 ; i < Filesl ; i++)
			{
				if( i == Filesl - 1)
				{
					FileNames += entity.getBxprocedure().get(i).get("name").toString();
				}else{
					FileNames += entity.getBxprocedure().get(i).get("name").toString()+" ; ";
				}
			}
			entity.setFileName(FileNames);//波形名称

			String validate=boxingService.validate(entity,"new");

			if(StringUtils.hasText(validate))
				return AjaxResult.failed(validate);

			//获取token
			String token = checkAdminToken.getTokenFormRequest(request);
			SysAdmin user = adminService.getAdminByToken(token);
			//获取登录名 并赋值
			String userName = user.getName();
			entity.setCreatorId(userName);

			//给提交和审核赋值初始值
			entity.setTijiao(false);
			entity.setShenhe(false);

			//获取当前日期
			Date currentDate = new Date();
			entity.setCreatedate(currentDate);//创建日期
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);    
			boolean rsg = boxingService.save(entity);
			if (rsg) {
				  return AjaxResult.success("system.insertSuccess");
			  }else {
				  return AjaxResult.failed("system.insertFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}


	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/getUpdateInfo")
	@ApiOperation(value = "获取波形程序管理对象", notes = "作者：Wonder")
	public AjaxResult<Boxing> getUpdateInfo(@RequestBody Map<String,Object> map){
		if(map==null) return AjaxResult.failed("system.parameterError");
		Long fid=Long.parseLong(map.get("fid").toString());
		Boxing boxing=boxingService.getById(fid);
		if(boxing.getBxprocedure_table()!=null)
			boxing.setBxprocedure(JSON.parseObject(boxing.getBxprocedure_table()
					,new ArrayList<Map<String, Object>>().getClass()));

		if (null!=boxing ) {
			return AjaxResult.success(boxing);
		}else {
			return AjaxResult.failed("system.parameterError");
		}

	}

	/**
	 * @explain 修改
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<Boxing> update(HttpServletRequest request , @RequestBody Boxing entity) throws Exception {
		if (null!=entity)
		{
			String FileNames = "";
			//System.out.println(JSON.toJSONString(entity.getBxprocedure().get(0).get("url")));
			if(entity.getBxprocedure()!=null)
				entity.setBxprocedure_table(JSON.toJSON(entity.getBxprocedure()).toString());
			int Filesl = entity.getBxprocedure().size();
			//拼接波形名称
			for( int i = 0 ; i < Filesl ; i++)
			{
				if( i == Filesl - 1)
				{
					FileNames += entity.getBxprocedure().get(i).get("name").toString();
				}else{
					FileNames += entity.getBxprocedure().get(i).get("name").toString()+" ; ";
				}
			}
			entity.setFileName(FileNames);//波形名称
			String validate=boxingService.validate(entity,"update");
			if(StringUtils.hasText(validate))
				return AjaxResult.failed(validate);

			//获取token
			String token = checkAdminToken.getTokenFormRequest(request);
			SysAdmin user = adminService.getAdminByToken(token);
			//获取登录名 并赋值
			String userName = user.getName();
			entity.setModifierId(userName);

			//获取当前日期
			Date currentDate = new Date();
			entity.setModifydate(currentDate);//修改日期
			//获取提交状态
			boolean tj = entity.getTijiao();

			boolean rsg ;
			//当数据未提交成功时执行修改操作
			if(tj != true){
				rsg = boxingService.updateById(entity);
			}else{
				rsg = false;
			}
			//boolean rsg = boxingService.updateById(entity);
			if (rsg) {
				return AjaxResult.success("system.updateSuccess");
			}else {
				return AjaxResult.failed("system.updateFailed");
			}
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}

	/**
	 * @explain 提交
	 */
	@PostMapping("/boxing_tijiao")
	@ApiOperation(value = "修改提交状态", notes = "作者：Wonder")
	public AjaxResult<Boolean> isTiJiao(@RequestBody Map<String,Object> map){
		Long fid = Long.parseLong(map.get("fid").toString());
		boolean res =  boxingService.boxingTiJiao(fid);
		if (res){
			return AjaxResult.success("提交成功");
		} else {
			return AjaxResult.failed("已经提交或审核过了");
		}
	}


	/**
	 * @explain 撤销
	 */
	@PostMapping("/boxing_chexiao")
	@ApiOperation(value = "修改提交状态", notes = "作者：Wonder")
	public AjaxResult<Boolean> isCheXiao(@RequestBody Map<String,Object> map){
		Long fid = Long.parseLong(map.get("fid").toString());
		boolean res =  boxingService.boxingCheXiao(fid);
		if (res){
			return AjaxResult.success("撤销成功");
		} else {
			return AjaxResult.failed("数据已经审核或数据未提交");
		}
	}


	/**
	 * @explain 审核
	 */
	@PostMapping("/boxing_shenhe")
	@ApiOperation(value = "修改审核状态", notes = "作者：Wonder")
	public AjaxResult<Boolean> isShenhe(HttpServletRequest request ,@RequestBody Map<String,Object> map) throws Exception {
		Long fid = Long.parseLong(map.get("fid").toString());

		Boxing boxing = boxingDao.selectById(fid);
		//获取token
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		//获取登录名 并赋值
		String userName = user.getName();
		boxing.setAuditorId(userName);
		boxingService.updateById(boxing);


		boolean res =  boxingService.boxingShenHe(fid);
		if (res){
			//要访问的url
			String tpprocedure_table = boxing.getBxprocedure_table();
			ObjectMapper objectMapper = new ObjectMapper();
			JsonNode jsonNode = objectMapper.readTree(tpprocedure_table);
			String url = String.valueOf(jsonNode.get(0).get("url"));
			//获取到的字符串会多一个双引号,所以截取一下
			String subUrl = url.substring(1, url.lastIndexOf('"'));
			//获取到文件信息转换成byte数组
			byte[] fileStream = FileUtils.getFileStream(subUrl);
			//获取到附件的id(波形的id)
			Boxing boxing1 = boxingService.getOne(new QueryWrapper<Boxing>().like("bxprocedure",subUrl));
//			SysFile sysFile = sysFileService.getOne(new QueryWrapper<SysFile>().eq("filepath",subUrl));
			Long fid1 = boxing1.getFid();

			//发送到mqtt
			providerConfig.publish(1,true,"awf_wf_data/" + fid1, fileStream);

			return AjaxResult.success("审核成功");
		} else {
			return AjaxResult.failed("还未提交或者已经审核");
		}
	}


	/**
	 * @explain 反审核
	 */
	@PostMapping("/boxing_fanshenhe")
	@ApiOperation(value = "修改审核状态", notes = "作者：Wonder")
	public AjaxResult<Boolean> isFanshenhe(@RequestBody Map<String,Object> map){
		Long fid = Long.parseLong(map.get("fid").toString());
		boolean res =  boxingService.boxingFanShenHe(fid);
		if (res){
			return AjaxResult.success("反审核成功");
		} else {
			return AjaxResult.failed("数据未审核或数据未提交");
		}
	}





	/**
	 * @explain 删除
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "删除", notes = "作者：Wonder")
	public AjaxResult<Boxing> delete(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed("system.parameterError");
		String ids=map.get("fid").toString();
		ids=StringUtils.remove(ids, '[');
		ids=StringUtils.remove(ids, ']');
		String[] deleteIds=StringUtils.split(ids, ',');
		List<Long> idList=new ArrayList<>();
		for(int i=0;i<deleteIds.length;i++)
		{
			idList.add( Long.parseLong(deleteIds[i].trim()));//整数数组
		}

		Boxing boxing = boxingDao.selectById(ids);
		//获取提交和审核状态
		String tj = boxing.getTijiao().toString();
		boolean rsg ;
		if(tj != "true"){
			rsg = boxingService.removeBatchByIds(idList);
		}else{
			rsg = false;
		}

		if (rsg) {
			return AjaxResult.success("删除成功");
		}else {
			return AjaxResult.failed("已审核或提交的数据不允许删除");
		}
	}


	/**
	 * @explain 查看对象明细
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "获取波形程序管理对象明细", notes = "作者：Wonder")
	public AjaxResult<Boxing> detail(@RequestBody Map<String,Object> map){
		if(map==null) return AjaxResult.failed("system.parameterError");
		Long fid=Long.parseLong(map.get("fid").toString());
		Boxing boxing=boxingService.getById(fid);
		if(boxing.getBxprocedure_table()!=null)
			boxing.setBxprocedure(JSON.parseObject(boxing.getBxprocedure_table()
					,new ArrayList<Map<String, Object>>().getClass()));
		if (null!=boxing ) {
			return AjaxResult.success(boxing);
		}else {
			return AjaxResult.failed("system.parameterError");
		}

	}


	/**
	 * 根据波形编码或者波形名称获取到波形列表
	 * @param
	 * @return
	 */
	@ApiOperation(value = "根据key获取波形")
	@PostMapping(value = "/get_boxing_by_key")
	public AjaxResult<Map<String,Object>> getListByKey(@RequestBody Map<String,Object> map) {
		String key = map.get("key").toString();
		int pageSize = Integer.parseInt(map.get("pageSize").toString());
		Map<String, Object> data = boxingService.getBoXingByKey(key, pageSize);
		if (null != data ) {
			return AjaxResult.success(data);
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}

	/**
	 * 获取波形列表
	 * @param
	 * @return
	 */
	@ApiOperation(value = "获取波形列表")
	@PostMapping(value = "/get_boxing_list")
	public AjaxResult<Map<String,Object>> getBoXingList(@RequestBody Map<String,Object> map) {

		List<Boxing> boxings = boxingDao.selectList(null);
		if (null != boxings ) {
			Map<String,Object> data = new HashMap<>();
			data.put("data",boxings);
			return AjaxResult.success(data);
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}

	@ApiOperation(value = "mqtt重新登录")
	@PostMapping("/mqtt_login")
	public void mqttLogin(){
		mqttReceiveConfig.init();
	}
}